package qcmPlus.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;

import qcmPlus.beans.Question;
import qcmPlus.beans.Questionnaire;
import qcmPlus.beans.Reponse;
import qcmPlus.tools.HibernateUtil;

public class QuestionDao extends HibernateUtil {

	private List<Question> listeQuestions = new ArrayList<Question>();

	public Question getQuestion(int id) 
	{
		Session s = HibernateUtil.currentSession();
		Question question = (Question) s.get(Question.class, id);
		HibernateUtil.closeSession();
		return question;
	}

	@SuppressWarnings("unchecked")
	public List<Question> liste(int idQuestionnaire) 
	{

		Session s = HibernateUtil.currentSession();
		listeQuestions = (ArrayList<Question>) s.createQuery(
				"from Question where ID_QUESTIONNAIRE=" + idQuestionnaire
						+ " order by ID_QUESTION asc").list();

		HibernateUtil.closeSession();
		return listeQuestions;
	}

	public String insertion(Questionnaire qn, String intitule,
			List<Reponse> listeReponses) {
		Session s = HibernateUtil.currentSession();
		Question question = new Question(qn, intitule, listeReponses);
		s.save(question);
		HibernateUtil.closeSession();
		return "ok";
	}

	public String modification(Question question) {
		Session s = HibernateUtil.currentSession();

		s.update(question);
		for (Reponse r : question.getListeReponses()) {
			s.update(r);
		}
		HibernateUtil.closeSession();
		return "ok";

	}
	
	public String suppression(Question question) {
		Session s = HibernateUtil.currentSession();
		
		for (Reponse r : question.getListeReponses()) {
			s.delete(r);
		}
		s.delete(question);
		HibernateUtil.closeSession();
		return "ok";
	}

	public List<Question> getListeQuestions() {
		return listeQuestions;
	}

	public void setListeQuestions(List<Question> listeQuestions) {
		this.listeQuestions = listeQuestions;
	}

	

}
